package com.home.andromotic;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.home.andromotic.model.IOIODevice;

public class ActividadRegistroDispositivo extends Activity {

	private AndromoticDbHelper dbHelper;
	private int zonaDevice = -1;
	private String nameZonaDevice = "default";
	private int grupoPerfil;
	private String[] infoBD;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_agregar_dispositivo_registro);
		dbHelper = new AndromoticDbHelper(getApplicationContext());

		// intento 2
		grupoPerfil = -1;
		Intent externo = getIntent();
		Bundle b = externo.getExtras();
		grupoPerfil = b.getInt("perfil");

		ListView listView = (ListView) findViewById(R.id.registro_zone_list);
		String[] values = new String[] { "Entrada", "Sala", "Comedor",
				"Habitacion", "Jardin", "Otro espacio" };

		// First paramenter - Context
		// Second parameter - Layout for the row
		// Third parameter - ID of the View to which the data is written
		// Forth - the Array of data
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, android.R.id.text1, values);

		// Assign adapter to ListView
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(
						getApplicationContext(),
						"Selecciono: "
								+ ((ArrayAdapter<String>) parent.getAdapter())
										.getItem(position), Toast.LENGTH_SHORT)
						.show();
				zonaDevice = position;
			}
		});

		// lanzar la app de QR
		final IntentIntegrator integrator = new IntentIntegrator(this);
		Button btnQr = (Button) findViewById(R.id.device_add_btn_qr);
		btnQr.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				integrator.initiateScan();
			}
		});

		// lanzar el Dialog
		Button btnSerie = (Button) findViewById(R.id.device_add_btn_serie);
		btnSerie.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				createdDialog();
			}
		});

		// Aceptar es agregar a la base de datos, lanzar el result y cerrar
		Button btnAceptar = (Button) findViewById(R.id.registro_btn_aceptar);
		btnAceptar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				EditText deviceName = (EditText) findViewById(R.id.registro_device_name);
				IOIODevice temp = (createdDevice(infoBD, zonaDevice, deviceName.getText().toString()));
				if( temp != null ){
				dbHelper.setDevice(temp);
				Toast.makeText(getApplicationContext(), "Dispositivo agregado",
						Toast.LENGTH_SHORT).show();
				finish();
				}
			}
		});

		// Cancelar lanzar el result incorrecto y finalizar
		Button btnCancelar = (Button) findViewById(R.id.registro_btn_cancelar);
		btnCancelar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(),
						"Dispositivo no agregado", Toast.LENGTH_SHORT).show();
				finish();
			}
		});
	}// OnCreate

	// ESTE METODO RECIBE EL PAQUETE AGREGADO
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		IntentResult scanResult = IntentIntegrator.parseActivityResult(
				requestCode, resultCode, data);

		if (scanResult != null) {
			if (resultCode == RESULT_OK) {
				// Intent intento = data;
				String id = scanResult.getContents();
				Toast.makeText(getApplicationContext(),
						"Procesando: " + scanResult.getContents(),
						Toast.LENGTH_LONG).show();
				TextView deviceCode = (TextView) findViewById(R.id.registro_device_code);
				deviceCode.setText(id);

				infoBD = new String[id.length()];
				infoBD[0] = id;
				for (int i = 1; i < id.length(); i++) {
					infoBD[i] = "" + id.charAt(i - 1);
				}
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(), "Se cancelo la accion",
						Toast.LENGTH_LONG).show();
			}
		} else {
			Toast.makeText(getApplicationContext(), "No se recibio nada",
					Toast.LENGTH_LONG).show();
		}
	}

	// Arma el paquete para entregar a la BD
	private IOIODevice createdDevice(String[] datos, int zone, String nombre) {
		try {
			int tipo = Integer.parseInt(datos[1]);
			int in_out = Integer.parseInt(datos[2]);
			int valores = Integer.parseInt(datos[3]);
			int min_val = Integer.parseInt(datos[4]);
			int max_val = Integer.parseInt(datos[5]);
			int state = Integer.parseInt(datos[5]);
			int id = Integer.parseInt(datos[0]);
			if(zone!=-1){
			return new IOIODevice(tipo, in_out, valores, min_val, max_val,
					state, id, zone, nombre);
			}else{
				throw new Exception();				
			}
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"infromacion errada o incompleta", Toast.LENGTH_SHORT).show();
		} 
		
		return null;
		
	}

	// -------------------------

	public void createdDialog() {
		// inflater
		LayoutInflater factory = LayoutInflater.from(this);
		final View alertDialogView = factory.inflate(
				R.layout.layout_dialog_registro_serie, null);
		// creacion del dialogo
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		// seleccion de la vista
		adb.setView(alertDialogView);
		// seleccion del titulo
		adb.setTitle("Registro de modulo por serie");
		// Seleccion dibujable
		adb.setIcon(android.R.drawable.ic_dialog_alert);
		// listeners
		adb.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				EditText et = (EditText) alertDialogView
						.findViewById(R.id.dialogoEditable);
				Toast.makeText(getApplicationContext(), et.getText(),
						Toast.LENGTH_SHORT).show();
				TextView deviceCode = (TextView) findViewById(R.id.registro_device_code);

				String id = et.getText().toString();
				deviceCode.setText(id);
				infoBD = new String[id.length()];
				infoBD[0] = id;
				for (int i = 1; i < id.length(); i++) {
					infoBD[i] = "" + id.charAt(i - 1);
				}
			}
		});
		adb.setNegativeButton("Cancelar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
		adb.show();
	}

} // Clase